<?php

/**
 * This is the model class for table "{{ord_comment}}".
 *
 * The followings are the available columns in table '{{ord_comment}}':
 * @property integer $zoc_id
 * @property string $zo_id
 * @property integer $zp_id
 * @property integer $zm_id
 * @property integer $zm_id_sent
 * @property string $zoc_spe
 * @property string $zoc_content
 * @property string $zoc_pe
 * @property integer $zoc_composite
 * @property integer $zoc_product
 * @property integer $zoc_service
 * @property integer $zoc_express
 * @property integer $zoc_sum
 * @property integer $zoc_status
 * @property integer $zoc_view
 * @property integer $inputtime
 * @property integer $updatetime
 */
class OrdComment extends CActiveRecord
{
	//商品名称,用于筛选
	public $zp_name;
	
	//会员名称,用于筛选
	public $zm_name;
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return OrdComment the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{ord_comment}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('zo_id', 'required'),
			array('zp_id, zm_id, zp_id, zm_id_sent, zop_id, zoc_composite, zoc_product, zoc_service, zoc_express, zoc_sum, zoc_status, zoc_type, zoc_view, inputtime, updatetime', 'numerical', 'integerOnly'=>true),
			array('zo_id', 'length', 'max'=>20),
			array('zoc_spe', 'length', 'max'=>50),
			array('zoc_content, zoc_pe', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('zoc_id, zo_id, zp_id, zm_id, zm_id_sent, zoc_spe,zop_id, zoc_content, zp_name, zm_name, zoc_pe, zoc_product, zoc_service, zoc_express, zoc_sum, zoc_status, zoc_view, inputtime, updatetime', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
				'order'=>array(self::BELONGS_TO,'Order','zo_id'),
				'product'=>array(self::BELONGS_TO,'OrdProduct','zop_id'),
				'products'=>array(self::BELONGS_TO,'Product','zp_id'),
				'tomember'=>array(self::BELONGS_TO,'Member','zm_id'),//被评价会员
				'tocompany'=>array(self::BELONGS_TO,'Company','zm_id'),//被评价商家
				'sentmember'=>array(self::BELONGS_TO,'Member',array('zm_id_sent'=>'zm_id')),//发起评价会员
				'sentcompany'=>array(self::BELONGS_TO,'Company',array('zm_id_sent'=>'zm_id')),//发起评价商家
		);
	}

	/**
	 * 我收到或发出的评价，返回数组,包含分页对象、包含订单商品，订单，店铺等信息
	 * @$type 1.我是买家 2.我是商家
	 * @$fromorto 1.to我 2.from我
	 * @$level 0.全部 1.差评 2.中评 3.好评
	 * @return array 
	 */
	public function getComments($memberid,$type,$fromorto,$level=0,$pageSize=10)
	{
		$levelCondition = $level ? ' and c.zoc_sum='.$level :' ';
		if($fromorto==1){
			$countSql = 'select count(c.zoc_id) as amount from {{ord_comment}} c left join {{order}} o on o.zo_id=c.zo_id left join {{ord_product}} op on op.zo_id=c.zo_id and op.zo_id=c.zo_id left join {{company}} company on op.zm_id=company.zm_id where c.zm_id='.$memberid. $levelCondition.' and c.zoc_type='.$type;
			$sql = 'select c.*,c.inputtime as input,op.*,o.*,company.* from {{ord_comment}} c left join {{order}} o on o.zo_id=c.zo_id left join {{ord_product}} op on op.zo_id=c.zo_id and op.zo_id=c.zo_id left join {{company}} company on op.zm_id=company.zm_id where c.zm_id='.$memberid.$levelCondition.' and c.zoc_type='.$type;
		}else{
			$type = $type==1 ? 2 : 1;
			if($type==2){
				$countSql = 'select count(c.zoc_id) as amount from {{ord_comment}} c left join {{order}} o on o.zo_id=c.zo_id left join {{ord_product}} op on op.zo_id=c.zo_id and op.zo_id=c.zo_id left join {{company}} company on op.zm_id=company.zm_id where o.zm_id='.$memberid. $levelCondition.' and c.zoc_type='.$type;
				$sql = 'select c.*,c.inputtime as input,op.*,o.*,company.* from {{ord_comment}} c left join {{order}} o on o.zo_id=c.zo_id left join {{ord_product}} op on op.zo_id=c.zo_id and op.zo_id=c.zo_id left join {{company}} company on op.zm_id=company.zm_id where o.zm_id='.$memberid. $levelCondition.' and c.zoc_type='.$type;
			}else{
				$countSql = 'select count(c.zoc_id) as amount from {{ord_comment}} c left join {{order}} o on o.zo_id=c.zo_id left join {{ord_product}} op on op.zo_id=c.zo_id and op.zo_id=c.zo_id left join {{company}} company on op.zm_id=company.zm_id where op.zm_id='.$memberid. $levelCondition.' and c.zoc_type='.$type;
				$sql = 'select c.*,c.inputtime as input,op.*,o.*,company.* from {{ord_comment}} c left join {{order}} o on o.zo_id=c.zo_id left join {{ord_product}} op on op.zo_id=c.zo_id and op.zo_id=c.zo_id left join {{company}} company on op.zm_id=company.zm_id where op.zm_id='.$memberid. $levelCondition.' and c.zoc_type='.$type;
			}
		}
		$amount = Yii::app()->db->createCommand($countSql)->queryScalar();
		$pager = new CPagination($amount);
		$pager->pageSize = $pageSize;
		$sql .= ' group by c.zoc_id order by c.zoc_id desc ';
		$sql .= ' limit '.$pager->currentPage*$pager->pageSize.','.$pager->pageSize.' ';
		$comments = $amount = Yii::app()->db->createCommand($sql)->queryAll();
		//好中差评对应的显示效果
		foreach($comments as $key=>$comment){
			switch ($comment['zoc_sum']){
				case 1 : $comments[$key]['cssClass'] = 'rate_bad';
						 $comments[$key]['text'] = '差评';//评论内容为空时显示
				break;
				case 2 : $comments[$key]['cssClass'] = 'rate_normal';
						 $comments[$key]['text'] = '中评';
				break;
				case 3 : $comments[$key]['cssClass'] = 'rate_good';
						 $comments[$key]['text'] = '好评';
				break;
				default:;break;
			}
		}
		$data['pager'] = $pager;
		$data['comments'] = $comments;
		return $data;
	}

	/**
	 *评价类型
	 */
	public function getCommentType($type=null){
		if($type==null){
			return array(
					''=>'所有评价',
					'1'=>'差评',
					'2'=>'中评',
					'3'=>'好评',
				);
		}else{
			$level = $this->getCommentType();
			if(array_key_exists($type,$level))
				return $level[$type];
		}
	}
	
	/**
	 * 店家平均评分统计
	 * @return array('产品描述评分','服务评分','物流评分','综合评分')
	 */
	public function getCmpAvg($cmpid=null)
	{
		$cmpid = empty($cmpid)?company::model()->getCmpUserId():$cmpid;
		$comment = Yii::app()->db->createCommand()
					->select('AVG(zoc_product) as avg_product,AVG(zoc_service) as avg_service, AVG(zoc_express) as avg_express')
					->from("{{ord_comment}}")
					->where('zm_id=:zmid and zoc_type=2 ', array(':zmid'=>$cmpid))
					->queryRow();
		$avg_unite = ($comment['avg_product']+$comment['avg_service']+$comment['avg_express'])/3;
		return array(
				'avg_describe'=>number_format($comment['avg_product'],2,'.',''),
				'avg_service'=>number_format($comment['avg_service'],2,'.',''),
				'avg_express'=>number_format($comment['avg_express'],2,'.',''),
				'avg_unite'=>number_format($avg_unite,2,'.',''),
				);
	}
	
	/**
	 * 店铺评分统计
	 * @param $cmpid店铺ID
	 * @return $array()
	 */
	public function getCmpPoint($cmpid){

		$total = $this->countByAttributes(array('zm_id'=>$cmpid,'zoc_type'=>2));//评论总数
		
		//服务评分,统计每个分值的数量
		$service['5'] = $this->countByAttributes(array('zm_id'=>$cmpid,'zoc_type'=>2,'zoc_service'=>5));//5分
		$service['4'] = $this->countByAttributes(array('zm_id'=>$cmpid,'zoc_type'=>2,'zoc_service'=>4));//4分
		$service['3'] = $this->countByAttributes(array('zm_id'=>$cmpid,'zoc_type'=>2,'zoc_service'=>3));//3分
		$service['2'] = $this->countByAttributes(array('zm_id'=>$cmpid,'zoc_type'=>2,'zoc_service'=>2));//2分
		$service['1'] = $this->countByAttributes(array('zm_id'=>$cmpid,'zoc_type'=>2,'zoc_service'=>1));//1分
		
		//产品描述评分,统计每个分值的数量
		$describe['5'] = $this->countByAttributes(array('zm_id'=>$cmpid,'zoc_type'=>2,'zoc_product'=>5));//5分
		$describe['4'] = $this->countByAttributes(array('zm_id'=>$cmpid,'zoc_type'=>2,'zoc_product'=>4));//4分
		$describe['3'] = $this->countByAttributes(array('zm_id'=>$cmpid,'zoc_type'=>2,'zoc_product'=>3));//3分
		$describe['2'] = $this->countByAttributes(array('zm_id'=>$cmpid,'zoc_type'=>2,'zoc_product'=>2));//2分
		$describe['1'] = $this->countByAttributes(array('zm_id'=>$cmpid,'zoc_type'=>2,'zoc_product'=>1));//1分
		
		//物流评分,统计每个分值的数量
		$express['5'] = $this->countByAttributes(array('zm_id'=>$cmpid,'zoc_type'=>2,'zoc_express'=>5));//5分
		$express['4'] = $this->countByAttributes(array('zm_id'=>$cmpid,'zoc_type'=>2,'zoc_express'=>4));//4分
		$express['3'] = $this->countByAttributes(array('zm_id'=>$cmpid,'zoc_type'=>2,'zoc_express'=>3));//3分
		$express['2'] = $this->countByAttributes(array('zm_id'=>$cmpid,'zoc_type'=>2,'zoc_express'=>2));//2分
		$express['1'] = $this->countByAttributes(array('zm_id'=>$cmpid,'zoc_type'=>2,'zoc_express'=>1));//1分
		//平均评分统计
		$comment = $this->getCmpAvg($cmpid);
		//产品描述评分百分比
		$comment['percent_describe'] = array(
					'5' => number_format($describe['5']/$total,2,'.',''),
					'4' => number_format($describe['4']/$total,2,'.',''),
					'3' => number_format($describe['3']/$total,2,'.',''),
					'2' => number_format($describe['2']/$total,2,'.',''),
					'1' => number_format($describe['1']/$total,2,'.',''),
				);
		//服务评分百分比
		$comment['percent_service'] = array(
					'5' => number_format($service['5']/$total,2,'.',''),
					'4' => number_format($service['4']/$total,2,'.',''),
					'3' => number_format($service['3']/$total,2,'.',''),
					'2' => number_format($service['2']/$total,2,'.',''),
					'1' => number_format($service['1']/$total,2,'.',''),
				);
		//服务评分百分比
		$comment['percent_express'] = array(
					'5' => number_format($express['5']/$total,2,'.',''),
					'4' => number_format($express['4']/$total,2,'.',''),
					'3' => number_format($express['3']/$total,2,'.',''),
					'2' => number_format($express['2']/$total,2,'.',''),
					'1' => number_format($express['1']/$total,2,'.',''),
				);
		//讨论总数 
		$comment['total'] = $total;
		return  $comment;
	}
	
	/**
	 * 产品平均评分统计
	 * @return array('产品描述评分','服务评分','物流评分','综合评分')
	 */
	public function getProAvg($zp_id=null)
	{
		$zp_id = empty($zp_id)?$zp_id:$zp_id;
		$comment = Yii::app()->db->createCommand()
					->select('AVG(zoc_product) as avg_product,AVG(zoc_service) as avg_service, AVG(zoc_express) as avg_express')
					->from("{{ord_comment}}")
					->where('zp_id=:zpid and zoc_type=2 ', array(':zpid'=>$zp_id))
					->queryRow();
		$avg_unite = ($comment['avg_product']+$comment['avg_service']+$comment['avg_express'])/3;

		return array(
				'avg_describe'=>number_format($comment['avg_product'],2,'.',''),
				'avg_service'=>number_format($comment['avg_service'],2,'.',''),
				'avg_express'=>number_format($comment['avg_express'],2,'.',''),
				'avg_unite'=>number_format($avg_unite,2,'.',''),
				'avg_star'=>$this->star(number_format($avg_unite,2,'.','')),
				);
	}
	
	/**
	 * 星星值
	 * @return 返回星星值
	 */
	public function star($nums){

		$point=$nums;
		if( $point > 0 && $point < 0.5){
			$star	=	'00';//五星
		}else if($point >= 0.5 && $point < 1){
			$star	=	'05';//半星
		}else if($point >= 1 && $point < 1.5){
			$star	=	'10';//1星
		}else if($point >= 1.5 && $point < 2){
			$star	=	'15';//1.5星
		}else if($point >= 2 && $point < 2.5){
			$star	=	'20';//2星
		}else if($point >= 2.5 && $point < 3){
			$star	=	'25';//2.5星
		}else if($point >= 3 && $point < 3.5){
			$star	=	'30';//3星
		}else if($point >= 3.5 && $point < 4){
			$star	=	'35';//3.5星
		}else if($point >= 4 && $point < 4.5){
			$star	=	'40';//4星
		}else if($point >= 4.5 && $point < 5){
			$star	=	'45';//4.5星
		}else if($point == 5){
			$star	=	'50';//5星
		}else{
			$star	=	'00';//5星
		}
		return $star;
	}
	/**
	 * 信用统计，返回好中差评数组，键0：总数 键1：差评 键2：中评 键3：好评，如$return[3]['in_a_week']为一周内好评数，以此类推
	 * @$type 1.会员 2.商家
	 * @return array 
	 */
	public function getAmountOfLevels($memberid,$type)
	{
		$criteria = new CDbCriteria();
		$criteria->compare('zm_id', $memberid);
		$criteria->compare('zoc_view', 1);
		$criteria->compare('zoc_type', $type);
		$criteria->select = 'zoc_sum,inputtime';
		$records = $this->findAll($criteria);
		$credit = array();
		for ($i = 0; $i <= 3; $i++)
		{
			$credit[$i]['in_a_week']          = 0;
			$credit[$i]['in_a_month']         = 0;
			$credit[$i]['in_three_month']     = 0;
			$credit[$i]['three_month_before'] = 0;
			$credit[$i]['total']              = 0;
		}
		foreach($records as $comment){
			
			$eval = $comment['zoc_sum'];
			$credit[$eval]['total']++;
			$credit[0]['total']++;
			// 天数
			$time = (time()-$comment->inputtime)/(3600*24);
			if( $time<7 ){
				$credit[$eval]['in_a_week']++;
				$credit[0]['in_a_week']++;
			}elseif( $time<30 ){
				$credit[$eval]['in_a_month']++;
				$credit[0]['in_a_month']++;
			}elseif( $time<90 ){
				$credit[$eval]['in_three_month']++;
				$credit[0]['in_three_month']++;
			}elseif( $time>90 ){
				$credit[$eval]['three_month_before']++;
				$credit[0]['three_month_before']++;
			}
		}
		return $credit;
	}	 
	
	/**
	 * 信用统计，返回会员好评数
	 * @$type 1.会员 2.商家
	 * @return Number 
	 */
	public function getGoodAmount($memberid,$type)
	{
		$criteria = new CDbCriteria();
		$criteria->compare('zm_id', $memberid);
		$criteria->compare('zoc_sum', 3);
		$criteria->compare('zoc_view', 1);
		$criteria->compare('zoc_type', $type);
		$criteria->select = 'zoc_sum,inputtime';
		return $records = $this->count($criteria);
	}
	
	/**
	 * 信用统计，返回会员信用等级
	 * @$type 1.会员 2.商家
	 * @return Number 
	 */
	public function getCreditLevel($memberid,$type){
		$credit = $this->getGoodAmount($memberid,$type);
		$levels=array(
				0 => array(4,10,'red_1'),//红心
				1 => array(11,40,'red_2'),
				2 => array(41,90,'red_3'),
				3 => array(91,150,'red_4'),
				4 => array(151,250,'red_5'),
				5 => array(251,500,'blue_1'),//钻石
				6 => array(501,1000,'blue_2'),
				7 => array(1001,2000,'blue_3'),
				8 => array(2001,5000,'blue_4'),
				9 => array(5001,10000,'blue_5'),
				10 => array(10001,20000,'cap_1'),//皇冠
				11 => array(20001,50000,'cap_2'),
				12 => array(50001,100000,'cap_3'),
				13 => array(100001,200000,'cap_4'),
				14 => array(200001,500000,'cap_5'),
				15 => array(500001,1000000,'gold_1'),//金冠
				16 => array(1000001,2000000,'gold_2'),
				17 => array(2000001,5000000,'gold_3'),
				18 => array(5000001,10000000,'gold_4'),
				19 => array(10000001,90000000,'gold_5'),
		);
		foreach($levels as $row){
			if($credit>=$row[0] && $credit<=$row[1]) {
				return $row[2];
			}
		}
	}

	/*
	 * 计算买家或卖家信用等级
	* @param int $credit  信用积分（好评数）
	*/
	function Level($credit){
		$levels=array(
				0 => array(4,10,'red_1'),//红心
				1 => array(11,40,'red_2'),
				2 => array(41,90,'red_3'),
				3 => array(91,150,'red_4'),
				4 => array(151,250,'red_5'),
				5 => array(251,500,'blue_1'),//钻石
				6 => array(501,1000,'blue_2'),
				7 => array(1001,2000,'blue_3'),
				8 => array(2001,5000,'blue_4'),
				9 => array(5001,10000,'blue_5'),
				10 => array(10001,20000,'cap_1'),//皇冠
				11 => array(20001,50000,'cap_2'),
				12 => array(50001,100000,'cap_3'),
				13 => array(100001,200000,'cap_4'),
				14 => array(200001,500000,'cap_5'),
				15 => array(500001,1000000,'gold_1'),//金冠
				16 => array(1000001,2000000,'gold_2'),
				17 => array(2000001,5000000,'gold_3'),
				18 => array(5000001,10000000,'gold_4'),
				19 => array(10000001,90000000,'gold_5'),
				20 => array(0,3,'red_1'),//无显示
		);
		foreach($levels as $row){
			if($credit>=$row[0] && $credit<=$row[1]) {
				return $row[2];
			}
		}
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'zoc_id' => 'Zoc',
			'zo_id' => 'Zo',
			'zop_id' => '订单产品ID',
			'zp_id' => 'Zp',
			'zm_id' => '被评论者',
			'zm_id_sent' => '发起评论者',
			'zoc_spe' => 'Zoc Spe',
			'zoc_content' => 'Zoc Content',
			'zoc_pe' => 'Zoc Pe',
			'zoc_composite' => '综合评分',
			'zoc_product' => 'Zoc Product',
			'zoc_service' => 'Zoc Service',
			'zoc_express' => 'Zoc Express',
			'zoc_type' => '评论类型',
			'zoc_totype' => '评论对象',//1评论订单,2评论商品
			'zoc_sum' => 'Zoc Sum',
			'zoc_status' => 'Zoc Status',
			'zoc_view' => 'Zoc View',
			'inputtime' => 'Inputtime',
			'updatetime' => 'Updatetime',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search($pageSize=10)
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->join = "";
		$criteria->compare('zoc_id',$this->zoc_id);
		$criteria->compare('zo_id',$this->zo_id,true);
		$criteria->compare('zop_id',$this->zop_id);
		$criteria->compare('zp_id',$this->zp_id);
		$criteria->compare('zm_id',$this->zm_id);
		$criteria->compare('zm_id_sent',$this->zm_id_sent);
		$criteria->compare('zoc_spe',$this->zoc_spe,true);
		$criteria->compare('zoc_content',$this->zoc_content,true);
		$criteria->compare('zoc_pe',$this->zoc_pe,true);
		$criteria->compare('zoc_composite',$this->zoc_composite);
		$criteria->compare('zoc_product',$this->zoc_product);
		$criteria->compare('zoc_service',$this->zoc_service);
		$criteria->compare('zoc_express',$this->zoc_express);
		$criteria->compare('zoc_type',$this->zoc_type);
		$criteria->compare('zoc_totype',$this->zoc_totype);
		$criteria->compare('zoc_sum',$this->zoc_sum);
		$criteria->compare('zoc_status',$this->zoc_status);
		$criteria->compare('zoc_view',$this->zoc_view);
		$criteria->compare('inputtime',$this->inputtime);
		$criteria->compare('updatetime',$this->updatetime);
		
		//跟据商品名称筛选
		if(!empty($this->zp_name)){
			$criteria->join .= ' LEFT JOIN {{product}} p ON p.zp_id=t.zp_id ';
			$criteria->addCondition("p.zp_name like '%".$this->zp_name."%'");
		}
		
		//跟据评论会员名称筛选
	   if(!empty($this->zm_name)){
			$criteria->join .= ' LEFT JOIN {{member}} m ON m.zm_id=t.zm_id_sent ';
			$criteria->addCondition("m.zm_name like '%".$this->zm_name."%'");
		}

		$criteria->order = " inputtime DESC ";//默认为时间倒序
		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
			'pagination'=>array('pageSize'=>$pageSize),
		));
	}
	
	protected function beforeSave(){
		if($this->isNewRecord){
			$this->inputtime = time();
		}else{
			$this->updatetime = time();
		}
		return true;
	}
}